package com.example.phone.home;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.phone.ProductDetails.Detail;
import com.example.phone.R;
import com.example.phone.bean.ParentCategory;
import com.example.phone.bean.Product;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;


public class HomeFragment extends Fragment implements View.OnClickListener {

    private View view;
    private ProgressBar home_progressBar;
    private ScrollView home_ScrollView;
    private List<Product> productList = new ArrayList<>();
    private List<Product> recommendProductList = new ArrayList<>();
    private List<ParentCategory> parentCategoryList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate( R.layout.fragment_home, container, false );
        initData();
        return view;
    }

    //初始化数据
    private void initData() {
        //回调匿名接口获取商品信息数据
        RequestData requestProductData = new RequestData(new RequestData.UpdateData() {
            @Override
            public void onSuccess(Object object) {
                productList = (List<Product>) object;
                //Log.d("==========list", "请求成功" + productList);
                recommend( view );
            }

            @Override
            public void onFail(String error) {
                //Log.d("==========home", "请求失败");
                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
            }
        });
        requestProductData.sendRequestAllInfo();

        //回调匿名接口获取商品分类信息
        RequestData requestParentCategory = new RequestData(new RequestData.UpdateData() {
            @Override
            public void onSuccess(Object object) {
                parentCategoryList = (List<ParentCategory>) object;
                //Log.d("==========home", "请求成功" + parentCategoryList);
                sort( view, parentCategoryList );
            }

            @Override
            public void onFail(String error) {
                //Log.d("==========home", "请求失败");
                Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
            }
        });
        requestParentCategory.sendRequestCategory();

        moreClick( view );
    }

    //设置分类
    private void sort(View view, final List<ParentCategory> parentCategoryList) {

        GridView gridview = (GridView) view.findViewById( R.id.home_sort );
        List<Integer> sortImg = Arrays.asList( R.drawable.huawei, R.drawable.xiaomi, R.drawable.oppo,
                R.drawable.vivo, R.drawable.iphone, R.drawable.samsung );
        ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < 6; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put( "ItemImage",  sortImg.get(i));
            map.put( "ItemText", "" + parentCategoryList.get( i ).getName() );
            meumList.add( map );
        }
        SimpleAdapter saItem = new SimpleAdapter( getActivity(),
                meumList, //数据源
                R.layout.sort_item, //xml实现
                new String[]{"ItemImage", "ItemText"}, //对应map的Key
                new int[]{R.id.ItemImage, R.id.ItemText} );  //对应R的Id

        //添加Item到网格中
        gridview.setAdapter( saItem );
        //添加点击事件
        gridview.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Intent intent = new Intent( getActivity().getApplicationContext(), SortActivity.class );
                Bundle bundle = new Bundle();
                bundle.putInt("categoryId", parentCategoryList.get( arg2 ).getId());
                intent.putExtras(bundle);
                //Log.d( "home",  shopSortList.get( arg2 ).getBrandName());
                getActivity().startActivity(intent);
            }}
        );

        home_progressBar = view.findViewById(R.id.home_progressBar);
        home_ScrollView = view.findViewById(R.id.home_scrollView);
        home_progressBar.setVisibility(View.GONE);
        home_ScrollView.setVisibility(View.VISIBLE);
    }

    //商品推荐
    private void recommend(View view) {
        LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService( LAYOUT_INFLATER_SERVICE );
        GridView gridSales = (GridView) view.findViewById( R.id.gridSales );
        GridView gridNew = (GridView) view.findViewById( R.id.gridNew );
        GridView gridBoutique = (GridView) view.findViewById( R.id.gridBoutique );

        Log.d("++++++homeFragment:", productList.size() + "");

        recommendProductList = productList.subList(0, 9);
        setGridView( gridSales, recommendProductList );

        recommendProductList = productList.subList(10, 19);
        setGridView( gridNew, recommendProductList);

        recommendProductList = productList.subList(20, 29);
        setGridView( gridBoutique,  recommendProductList);
    }

    //设置GirdView参数，绑定数据
    private void setGridView(GridView gridView, final List<Product> productList) {
        int size = productList.size();
        int length = 100;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics( dm );
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT );
        gridView.setLayoutParams( params ); // 设置GirdView布局参数,横向布局的关键
        gridView.setColumnWidth( itemWidth ); // 设置列表项宽
        gridView.setHorizontalSpacing( 5 ); // 设置列表项水平间距
        gridView.setStretchMode( GridView.NO_STRETCH );
        gridView.setNumColumns( size ); // 设置列数量=列表集合数
        GridViewAdapter adapter = new GridViewAdapter( getActivity(), productList );
        gridView.setAdapter( adapter );
        //添加监听事件
        gridView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Intent intent = new Intent( getActivity().getApplicationContext(), Detail.class );
                Bundle bundle = new Bundle();
                bundle.putInt("productId", productList.get(arg2).getId());
                intent.putExtras(bundle);
                startActivity( intent );
            }}
        );
    }

    //点击事件
    private void moreClick(View view) {
        TextView sales_more = view.findViewById( R.id.sales_more );
        TextView new_more = view.findViewById( R.id.new_more );
        TextView boutique_more = view.findViewById( R.id.boutique_more );

        sales_more.setOnClickListener( this );
        new_more.setOnClickListener( this );
        boutique_more.setOnClickListener( this );

    }

    //更多点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sales_more:
                Toast.makeText( getActivity(), "促销更多", Toast.LENGTH_SHORT ).show();
                break;
            case R.id.new_more:
                Toast.makeText( getActivity(), "新品更多", Toast.LENGTH_SHORT ).show();
                break;
            case R.id.boutique_more:
                Toast.makeText( getActivity(), "推荐更多", Toast.LENGTH_SHORT ).show();
                break;
        }
    }

}